package com.example.kotlindemo.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.kotlindemo.R
import com.example.kotlindemo.bean.MessageBean

/**
 * @功能:
 * @Creat 2020/4/12 20:37
 * @User Lmy
 * @Compony JinAnChang
 */
class MessageAdapter(val messageBean: ArrayList<MessageBean>) :
    RecyclerView.Adapter<MessageAdapter.MsgViewHolder>() {
    /**
     * 内部类使用inner关键词修饰
     * sealed class关键词用于表示密封类
     * 当修饰未密封类时  使用时需要判断继承密封类的所有分支
     */
    sealed class MsgViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        class LeftViewHolder(itemView: View) : MsgViewHolder(itemView) {
            val content: TextView = itemView.findViewById(R.id.tv_left)
        }

        class RightViewHolder(itemView: View) : MsgViewHolder(itemView) {
            val content: TextView = itemView.findViewById(R.id.tv_right)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        if (viewType == 0) {
            val view =
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.message_left_item, parent, false)
            MsgViewHolder.LeftViewHolder(view)
        } else {
            val view =
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.message_right_item, parent, false)
            MsgViewHolder.RightViewHolder(view)
        }

    override fun getItemCount() = messageBean.size
    override fun getItemViewType(position: Int) = messageBean[position].type

    override fun onBindViewHolder(holder: MsgViewHolder, position: Int) {
        val data = messageBean[position]
        when (holder) {
            is MsgViewHolder.LeftViewHolder -> {
                holder.content.text = data.content
            }
            is MsgViewHolder.RightViewHolder -> {
                holder.content.text = data.content
            }
        }
    }

}